import { Component, OnInit } from '@angular/core';
import { ArrayutilsService } from 'src/app/service/arrayutils.service';

@Component({
  selector: 'app-angularcode',
  templateUrl: './angularcode.component.html',
  styleUrls: ['./angularcode.component.css']
})
export class AngularcodeComponent implements OnInit {

  constructor(
    private arrayUtils:ArrayutilsService
  ) { }

  ngOnInit() {
  }

  treeCode:string='';


 



  testBuildCurNode(){
    this.buildDistArray([
      {
        "auto_key": 7,
        "schema_name": "atools",
        "table_name": "issue",
        "table_comment": "议题表",
        "column_name": "update_time",
        "column_type": "datetime",
        "data_type": "datetime",
        "column_comment": "最后一次修改时间"
      },
      {
        "auto_key": 8,
        "schema_name": "atools",
        "table_name": "issue",
        "table_comment": "议题表",
        "column_name": "update_user",
        "column_type": "varchar(50)",
        "data_type": "varchar",
        "column_comment": "最后一次修改的用户"
      },
      {
        "auto_key": 5,
        "schema_name": "atools",
        "table_name": "issue",
        "table_comment": "议题表",
        "column_name": "status",
        "column_type": "int(11)",
        "data_type": "int",
        "column_comment": "状态,默认0表示开启，1表示完结，2表示放弃"
      },
      {
        "auto_key": 9,
        "schema_name": "atools",
        "table_name": "projects",
        "table_comment": "项目列表",
        "column_name": "author",
        "column_type": "varchar(50)",
        "data_type": "varchar",
        "column_comment": "创建者"
      },
      {
        "auto_key": 10,
        "schema_name": "atools",
        "table_name": "projects",
        "table_comment": "项目列表",
        "column_name": "create_time",
        "column_type": "datetime",
        "data_type": "datetime",
        "column_comment": "创建时间,DB自动填充"
      },
      {
        "auto_key": 3696,
        "schema_name": "weixin_cloud",
        "table_name": "user_convent",
        "table_comment": "用户角色权限映射",
        "column_name": "tip",
        "column_type": "varchar(50)",
        "data_type": "varchar",
        "column_comment": "备注"
      },
      {
        "auto_key": 3697,
        "schema_name": "weixin_cloud",
        "table_name": "user_convent",
        "table_comment": "用户角色权限映射",
        "column_name": "user_weixin_id",
        "column_type": "bigint(20)",
        "data_type": "bigint",
        "column_comment": "微信人员id"
      },
      {
        "auto_key": 3698,
        "schema_name": "weixin_cloud",
        "table_name": "user_mill",
        "table_comment": "微信openid对应染厂",
        "column_name": "alarm_gas",
        "column_type": "tinyint(4)",
        "data_type": "tinyint",
        "column_comment": "天然气报警,默认0不通知"
      },
      {
        "auto_key": 3699,
        "schema_name": "weixin_cloud",
        "table_name": "user_mill",
        "table_comment": "微信openid对应染厂",
        "column_name": "createtime",
        "column_type": "datetime",
        "data_type": "datetime",
        "column_comment": "创建时间,DB自动填充"
      }
    ],['schema_name','table_name','column_name']);

  }

  levels = [];
  keyField = 'auto_key';


  testTreeMethod(){
    
  }

  buildDistArray(rs:any[],distFields:string[]){
    let i = 0;
    for(i=0;i<distFields.length;i++){
      let ele = [this.arrayUtils.buildDistArray(rs,distFields.slice(0,i+1)),distFields.slice(0,i+1)];
      this.levels.push(ele);
    }


    let tree = this.recursion(0,this.levels[0][0],this.levels[0][1]);
    console.log(tree);
  }

  recursion(level:number,curLevelArray:any[],distFields:string[]):any[]{
    let nodes = [];
    curLevelArray.forEach(ele => {
      let distField = distFields[distFields.length-1];
      let title = ele[distField];
      let node = {'title':title,'key':ele[this.keyField],'children':[]};

      let nextLevel = level + 1;
      let childrenNodes = [];
      if(nextLevel<this.levels.length){
        let subArray = this.arrayUtils.getSames(this.levels[nextLevel][0],ele,this.levels[level][1]);
        childrenNodes = this.recursion(nextLevel,subArray,this.levels[nextLevel][1]);
      }
      node.children = childrenNodes;
      nodes.push(node);
    });

    return nodes;
  }
  
  // buildDistArray(rs:any[],fields:string[]){
  //   let i = 0;
  //   for(i=0;i<fields.length;i++){
  //     let ele = [this.arrayUtils.buildDistArray(rs,fields.slice(0,i+1)),fields.slice(0,i+1)];
  //     this.levels.push(ele);
  //   }


  //   let tree = this.recursion(0,this.levels[0][0],this.levels[0][1]);
  //   console.log(tree);
  // }

  // recursion(level:number,curLevelArray:any[],fields:string[]):any[]{
  //   let nodes = [];
  //   curLevelArray.forEach(ele => {
  //     let distField = fields[fields.length-1];
  //     let title = ele[distField];
  //     let node = {'title':title,'key':ele[this.keyField],'children':[]};

  //     let nextLevel = level + 1;
  //     let childrenNodes = [];
  //     if(nextLevel<this.levels.length){
  //       let subArray = this.arrayUtils.getSames(this.levels[nextLevel][0],ele,this.levels[level][1]);
  //       childrenNodes = this.recursion(nextLevel,subArray,this.levels[nextLevel][1]);
  //     }
  //     node.children = childrenNodes;
  //     nodes.push(node);
  //   });

  //   return nodes;
  // }





  ge(){
    this.generateTreeCode(['schema_name','table_name','column_name'],'auto_key');
  }

/**
   * 要求传入的记录集必须有名称为 auto_key 的字段，在记录集中唯一自增
   * @param levels 从上到下的 level 对应的字段名称构成的字符串类型的数组
   * @param autoKeyField 数据库端查询获得的记录集中表示自增唯一的字段名称
   */
  generateTreeCode(levels:string[],autoKeyField:string){
    if( levels.length<=0 ) return;

    // 1. 构建多个空数组
    let code01='';// 最后一层其上的所有层分别生成一个空数组
    let flatArray:string[]=[];
    let i = 0;let j = 0;
    for(i = 0;i<levels.length-1;i++){
        let arrayName = 'lev' + i + '_' + levels[i]; 
        flatArray.push(arrayName);
        code01 = code01 + `\n\tlet ${arrayName} = [];`;
    }


    // 2. 向所有父节点的数组填充数据
    let code02 = '';
    code02 = code02 + 'rs.forEach(ele => {';
    for(i=0;i<flatArray.length;i++){
        code02 = code02 + `
        if(${flatArray[i]}.length<=0) ${flatArray[i]}.push({`
          for(j=0;j<=i;j++){
            code02 = code02 + `'value${j}':ele.${levels[j]},`
          }
        code02 = code02 + `'autoKey':ele.auto_key});
        let level${i}Exists = ${flatArray[i]}.some(
            (item,index,array) => {
                return item.value === ele.${levels[i]};
            }
        )
        if( !level${i}Exists ) ${flatArray[i]}.push({`
        for(j=0;j<=i;j++){
          code02 = code02 + `'value${j}':ele.${levels[j]},`
        }
        code02 = code02 + `'autoKey':ele.${autoKeyField}});`
    }
    code02 = code02 + `});`

    // 3. 没有构建出数据则退出
    let code03 = '';
    code03 = code03 + `
    if(${flatArray[0]}.length<=0){
      console.log('没有构建出数据！');
      return;
    }`;


    let code04 = '';
    code04 = code04 + `
    ${flatArray[0]}.forEach(ele0 => {
      let lev0Node = {'title':ele0.value0,'key':ele0.autoKey,'children':[],'origin':{'${levels[0]}':ele0.value0}};`

    if( levels.length>2 ){// 中间层数组过滤获得关联当前首层节点的数据，要求总体层数超过2层才有该逻辑
      for(i=1;i<levels.length-1;i++){
        code04 = code04 + `let lev${i}_Array = ${flatArray[i]}.filter((item)=>{`
        code04 = code04 + `return ` 
        for(j=0;j<levels.length-1;j++){
          code04 = code04 + `item.value${j}===ele0.`;
        }
        
        `item.dbName === eleDB.dbName;`
        code04 = code04 + `})`;
      }
    }

    code04 = code04 + `}`
    
    let codeString=`
    rs2Tree(rs:any[]):any[]{
      // 1. 构建父节点空数组
      ${code01}

      // 2. 填充父节点数组
      ${code02} 

      // 3. 没有构建出数据则退出
      ${code03}

      
      return null;
    }
    `
    this.treeCode = codeString;
  }

}
